<template>
  <div class="monitor-chart">
    <CardBox
      :title="tabsName"
      :showTab="true"
      :tabs="tabs"
      :tabItemIsActive="tab.id"
      @tab-change="onTabChange"
    ></CardBox>
    <div>
      <div class="content-container" v-show="tabsName === '观测统计'">
        <div class="chart-container" ref="monitorChart"></div>
      </div>
      <div class="content-container" v-show="tabsName === '观测成果'">
        <div class="carousel-container">
          <div class="carousel-images">
            <div
              class="carousel-image"
              v-for="(img, idx) in currentImages"
              :key="idx"
            >
              <img :src="img.url" alt="轮播图片" />
            </div>
          </div>
          <div class="carousel-dots">
            <span
              v-for="i in totalPages"
              :key="i"
              :class="{ active: i - 1 === currentPage }"
              @click="goToPage(i - 1)"
            ></span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts";
import CardBox from "@/components/Global/CardBox.vue";
let that;
export default {
  name: "MonitorChart",
  inject: ["imgUrl"], // 注入公共变量
  created() {
    that = this;
  },
  components: {
    CardBox,
  },
  data() {
    return {
      types: ["SY_WZGCZW", "SY_WZGCNLHW", "SY_WZGCNLSP", "SY_WZGCNLSW", "SY_WZGCSL", "SY_WZGCKC"],
      select: "SY_WZGCZW",
      images: [

      ],
      monitorChart: null,
      handleMonitorChartResize: null,
      monitorData: {
        categories: ["植物物候", "鸟类红外", "鸟类视频", "鸟类声纹", "兽类", "昆虫"],
        values: [1000, 600, 580, 800, 700],
        details: [
          { value: 322, label: "植物物候" },
          { value: 223, label: "鸟类红外" },
          { value: 223, label: "鸟类视频" },
          { value: 223, label: "鸟类声纹" },
          { value: 36, label: "兽类" },
          { value: 13, label: "昆虫" },
        ],
      },
      tabsName: "",
      tab:{
        id: "observerStatistics",
        name: "观测统计",
      },
      tabs: [
        {
          id: "observerStatistics",
          name: "观测统计",
        },
        {
          id: "observationResults",
          name: "观测成果",
        },
      ],
      currentPage: 0,
      timer: null,
      pageSize: 4,
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.images.length / this.pageSize);
    },
    currentImages() {
      const start = this.currentPage * this.pageSize;
      return this.images.slice(start, start + this.pageSize);
    },
  },
  mounted() {
    this.tabsName = this.tabs[0].name;
    this.$nextTick(() => {
      this.getData();
      this.getImage();
    });
    // this.startAutoPlay();
  },
  beforeDestroy() {
    // Clean up monitor chart
    if (this.monitorChart) {
      this.monitorChart.dispose();
      this.monitorChart = null;
    }
    if (this.handleMonitorChartResize) {
      window.removeEventListener("resize", this.handleMonitorChartResize);
    }
    clearInterval(this.timer);
  },
  methods: {
    getData() {
      this.$api.device.getClassifyStatistics().then((res) => {
        this.monitorData.values = res.values;
        this.monitorData.categories = res.categories;
        this.initMonitorChart();
      });
    },
    getImage() {
      this.$api.device.getWZGCCG(this.select).then((res) => {
        // this.images = [];
        while (this.images.length){
          this.images.pop();
        }
        if (res.imageIds) {
          var ids = res.imageIds.split(",");
          for (let i = 0; i < ids.length; i++) {
            this.images.push({ url: this.imgUrl + ids[i] });
          }
        }
      });
    },
    initMonitorChart() {
      if (!this.$refs.monitorChart) {
        console.warn("Monitor chart container not found");
        return;
      }

      // 如果已存在图表实例，先销毁
      if (this.monitorChart) {
        this.monitorChart.dispose();
      }

      const chartDom = this.$refs.monitorChart;
      const chart = echarts.init(chartDom);

      const option = {
        title: {
          subtext: "单位：条",
          top: -12,
          left: 10,
          subtextStyle: {
            color: "#fff",
            position: "top",
            fontFamily: "DIN Pro",
          },
        },
        backgroundColor: "transparent",
        grid: {
          left: "5%",
          right: "5%",
          top: "15%",
          bottom: "10%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.monitorData.categories,
          axisLine: {
            lineStyle: {
              color: "rgba(255, 255, 255, 0.3)",
            },
          },
          axisLabel: {
            color: "#fff",
            fontSize: 12,
            interval: 0,
            rotate: 0,
          },
        },
        yAxis: {
          type: "value",
          splitLine: {
            lineStyle: {
              color: "rgba(255, 255, 255, 0.1)",
            },
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "rgba(255, 255, 255, 0.3)",
            },
          },
          axisLabel: {
            color: "#fff",
            fontSize: 12,
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          backgroundColor: "rgba(0,24,106,0.9)",
          borderColor: "rgba(0,150,255,0.3)",
          textStyle: {
            color: "#fff",
            fontFamily: "DIN Pro",
          },
          formatter: function (params) {
            const data = params[0];
            return `${data.name}: ${data.value}`;
          },
        },
        series: [
          {
            data: this.monitorData.values,
            type: "bar",
            barWidth: "40%",
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#25CDE9" },
                { offset: 1, color: "rgba(37, 205, 233, 0.1)" },
              ]),
            },
            label: {
              show: true,
              position: "top",
              color: "#fff",
              fontSize: 12,
              fontFamily: "DIN Pro",
            },
          },
        ],
      };

      chart.setOption(option);
      chart.on("click", function (params) {
        that.select = that.types[params.dataIndex];
        that.tab=that.tabs[1];
        that.getImage();
        that.tabsName = "观测成果";
        console.log(params); // 这里可以处理点击事件，例如显示提示框等。
      });
      this.monitorChart = chart;

      // 添加自适应大小
      const handleResize = () => {
        chart && chart.resize();
      };
      window.addEventListener("resize", handleResize);
      this.handleMonitorChartResize = handleResize;

      // 确保图表立即适应容器大小
      this.$nextTick(() => {
        chart.resize();
      });
    },
    startAutoPlay() {
      this.timer = setInterval(() => {
        this.currentPage = (this.currentPage + 1) % this.totalPages;
      }, 10000);
    },
    goToPage(page) {
      this.currentPage = page;
    },
    onTabChange(tab) {
      console.log('tab-change事件触发，tab:', tab);
      this.tabsName = tab.name;
      this.tab=tab;
      console.log('tabsName已更新为:', this.tabsName);
    },
  },
};
</script>
<style lang="scss" scoped>
.monitor-chart {
  margin-bottom: 20px;
  border-radius: 4px;
  width: 100%;
}

.monitor-chart .content-container {
  height: 332px;
  width: 100%;
  overflow: hidden;
  .chart-container {
    height: 100%;
    width: 100%;
  }
}

.carousel-container {
  width: 100%;
  background: #0a3a5e;
  padding: 10px;
  border-radius: 10px;
}
.carousel-images {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.carousel-image {
  width: 48%;
  margin-bottom: 10px;
}
.carousel-image img {
  width: 100%;
  height: 140px;
  display: block;
  object-fit: cover;
  border-radius: 2px;
}
.carousel-dots {
  text-align: center;
}
.carousel-dots span {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #3a7ca5;
  margin: 0 4px;
  cursor: pointer;
  transition: background 0.3s;
}
.carousel-dots .active {
  background: #fff;
}
</style>
